home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / c / bchelp10.zip / TI659.ASC < prev    next >
Text File  |  1991-09-17  |  1KB  |  67 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.   PRODUCT  :  C++                                    NUMBER  :  659
  9.   VERSION  :  All
  10.        OS  :  PC DOS
  11.      DATE  :  September 17, 1991                       PAGE  :  1/1
  12.  
  13.     TITLE  :  An Example of Using qsort() in C++ Mode
  14.  
  15.  
  16.  
  17.  
  18.   Due to the strict type checking enforced by the C++ language, one
  19.   must  insure  that  the  types  of the parameters to qsort  match
  20.   exactly.
  21.  
  22.   The  types  of  the parameters passed to the compare function are
  23.   the area for grief here.  By using a typedef which  typecasts the
  24.   compare  function  to  have the types  required  by  the  ANSI  C
  25.   prototype for qsort(), C++ can be made to accept our code.
  26.  
  27.  
  28.   //---------------------------------------------------------------
  29.   // QSORTX.CPP - using qsort() in C++ mode
  30.  
  31.   #include <stdlib.h>
  32.  
  33.   typedef int (*cmp_func)(const void *, const void *);
  34.  
  35.   int compare( const int *one, const int *two )
  36.   {
  37.      if (*one > *two)
  38.         return  -1
  39.      else
  40.         return 1;
  41.   } // end of compare()
  42.  
  43.   int a[3] = { 50, 10, 20 };
  44.  
  45.   main()
  46.   {
  47.      qsort(a, 3, sizeof(a[0]), compare);   // Does not compile in C++
  48.      qsort(a, 3, sizeof(a[0]), (cmp_func)compare);  // Does compile
  49.   } // end of main()
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.